package com.onenine.app.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.onenine.app.R;
import com.onenine.app.activity.LoginActivity;
import com.onenine.app.activity.MainActivity;
import com.onenine.app.listener.OnLoginListener;
import com.onenine.app.request.ThirdCheckRequest;
import com.onenine.app.response.ThirdCheckResponse;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.UrlConfig;
import com.onenine.app.view.uppanel.SlidingUpPanelLayout;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.Toasty;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.ActivityUtils;
import com.onenine.common.util.FragmentUtils;
import com.onenine.common.util.KeyboardUtils;
import com.umeng.share.UMLogin;
import com.umeng.share.UMSharer;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

public class LoginMainFragment extends Fragment implements View.OnClickListener {

    private View mBtnWx, mBtnQQ, mBtnMobile;
    private View mTvMobile;
    private OnLoginListener mOnLoginListener;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mOnLoginListener = (OnLoginListener) getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login_main, container, false);
        mBtnWx = view.findViewById(R.id.btn_wx_login);
        mBtnQQ = view.findViewById(R.id.btn_qq_login);
        mBtnMobile = view.findViewById(R.id.btn_phone);
        mTvMobile = view.findViewById(R.id.tv_mobile);
        mBtnWx.setOnClickListener(this);
        mBtnQQ.setOnClickListener(this);
        mBtnMobile.setOnClickListener(this);
        mTvMobile.setOnClickListener(this);
        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_phone:
            case R.id.tv_mobile:
                FragmentUtils.replace(getFragmentManager()
                        , LoginMobileFragment.newInstance(), R.id.fl_content, true);
                break;
            case R.id.btn_wx_login:
                UMLogin.getUserInfo(getActivity(), SHARE_MEDIA.WEIXIN, new UMAuthListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {
                        mOnLoginListener.showLoading();
                    }

                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                        map.put("platform", DataType.WEIXIN_LOGIN + "");
                        checkThirdPhoneStatus(map);
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                        mOnLoginListener.dismissLoading();
                        authLoginFailure(share_media);
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {
                        mOnLoginListener.dismissLoading();
                        Toasty.showNormal("微信登录取消");
                    }
                });
                break;
            case R.id.btn_qq_login:
                UMLogin.getAuthorize(getActivity(), SHARE_MEDIA.QQ, new UMAuthListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {
                        mOnLoginListener.showLoading();
                    }

                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                        UMLogin.getUserInfo(getActivity(), SHARE_MEDIA.QQ, new UMAuthListener() {
                            @Override
                            public void onStart(SHARE_MEDIA share_media) {

                            }

                            @Override
                            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                                map.put("platform", DataType.QQ_LOGIN + "");
                                checkThirdPhoneStatus(map);
                            }

                            @Override
                            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                                Toasty.showNormal("QQ登录失败");
                                mOnLoginListener.dismissLoading();
                            }

                            @Override
                            public void onCancel(SHARE_MEDIA share_media, int i) {
                                Toasty.showNormal("QQ登录取消");
                                mOnLoginListener.dismissLoading();
                            }
                        });
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                        mOnLoginListener.dismissLoading();
                        authLoginFailure(share_media);
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {
                        mOnLoginListener.dismissLoading();
                        Toasty.showNormal("QQ授权取消");
                    }
                });
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        KeyboardUtils.hideSoftInput(getActivity());
        mOnLoginListener.getUpPanelLayout()
                .setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
    }

    /**
     * 授权失败
     *
     * @param shareMedia
     */
    private void authLoginFailure(SHARE_MEDIA shareMedia) {
        if (!UMSharer.getInstance().isInstall(getActivity(), shareMedia)) {
            //未安装相应手机客户端
            if (shareMedia == SHARE_MEDIA.WEIXIN) {
                Toasty.showNormal(R.string.wx_app_uninstall);
            } else if (shareMedia == SHARE_MEDIA.QQ) {
                Toasty.showNormal(R.string.qq_app_uninstall);
            }
        } else {
            if (shareMedia == SHARE_MEDIA.WEIXIN) {
                Toasty.showNormal(R.string.wx_auth_failure);
            } else if (shareMedia == SHARE_MEDIA.QQ) {
                Toasty.showNormal(R.string.qq_auth_failure);
            }
        }
    }

    /**
     * 检测第三方登录是否已绑定手机
     *
     * @param map
     */
    private void checkThirdPhoneStatus(final Map<String, String> map) {
        mOnLoginListener.replaceLoading("正在登录中...");
        final String openId = map.get("openid");
        OkRequest.getInstance().withUrl(UrlConfig.CHECK_THIRD_PHONE_BIND)
                .withRequest(new ThirdCheckRequest(openId))
                .doRequest(LoginActivity.class.getSimpleName(), new OkCallback<ThirdCheckResponse>() {
                    @Override
                    public void onResponse(ThirdCheckResponse response, String srcData) {
                        mOnLoginListener.dismissLoading();
                        if (response.isSuccess()) {
                            if (response.isBln() && response.isUserBln()) {
                                //已绑定直接登录成功
                                RcUser.getInstance()
                                        .setLoginType(Integer.parseInt(map.get("platform")))
                                        .setUserId(response.getUserId())
                                        .setSex(response.getSex())
                                        .applyUser();
                                if (getActivity() != null && !getActivity().isFinishing()) {
                                    ActivityUtils.startActivity(getActivity(), MainActivity.class);
                                    mOnLoginListener.finishActivity();
                                }
                            } else if (response.isUserBln()) {
                                //未绑定手机号
                                FragmentUtils.replace(getFragmentManager()
                                        , LoginMobileFragment.newInstance(response.getUserId(), openId), R.id.fl_content, true);
                            } else {
                                //未填写资料
                                FragmentUtils.replace(getFragmentManager()
                                        , LoginInputInfoFragment.newInstance(map), R.id.fl_content, true);
                            }
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }


}
